package com.jkc.xh.activities;

import android.content.Intent;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.jkc.xh.R;
import com.jkc.xh.constants.Constant;
import com.jkc.xh.manager.UserManager;
import com.jkc.xh.network.ApiClient;
import com.jkc.xh.network.RestCallBack;
import com.jkc.xh.network.models.ActiveservsResponse;
import com.jkc.xh.network.models.ActiveservsResponse.Server;
import com.jkc.xh.network.models.NoticeResponse;
import com.jkc.xh.network.models.RestError;
import com.jkc.xh.utils.CacheTools;
import com.jkc.xh.utils.SecurePreferences;
import com.jkc.xh.views.widget.ToastUtil;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.UiThread;
import org.androidannotations.annotations.ViewById;

import java.io.File;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;

import retrofit.Call;

/**
 * Created by wangjie28 on 2015/12/25.
 */
@EActivity(R.layout.activity_splash)
public class SplashActivity extends BaseActivity {
    @ViewById
    ImageView ivWelcome;

    @AfterViews
    void initViews() {
        showProgress("");
        new Thread(new Runnable() {
            @Override
            public void run() {
                String baseUrl = SecurePreferences.getInstance().getString("preference_current_server", ApiClient.BASE_URL);
                ApiClient.BASE_URL = baseUrl;
                boolean rst = testUrlWithTimeOut(baseUrl, 3000);
                if(!rst){
                    String activeServsStr = SecurePreferences.getInstance().getString("preference_active_servs", "");
                    if(!TextUtils.isEmpty(activeServsStr)){
                        List<Server> serverList = new Gson().fromJson(activeServsStr, new TypeToken<List<Server>>(){}.getType());
                        for(Server server : serverList){
                            if(testUrlWithTimeOut(server.getAddress(), 2000)){
                                ApiClient.BASE_URL = server.getAddress();
                                SecurePreferences.getInstance().edit().putString("preference_current_server", server.getAddress()).commit();
                                break;
                            }
                        }
                    }
                }

                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        closeProgress();
                        requestServers();
                        requestNotices();
                        String welcomePath = SecurePreferences.getInstance().getString(Constant.PREFERENCE_WELCOME_PIC_PATH,"");
                        welcomePath = null == welcomePath ? "" : welcomePath;
                        File welcomeImage = new File(welcomePath);
                        if (welcomeImage != null && welcomeImage.exists()) {
//                            Glide.with(SplashActivity.this).load(welcomeImage).into(ivWelcome);
                            final String link = SecurePreferences.getInstance().getString(Constant.PREFERENCE_WELCOME_LINK, "");
                            if (!TextUtils.isEmpty(link)) {
                                ivWelcome.setOnClickListener(new View.OnClickListener() {
                                    @Override
                                    public void onClick(View v) {
                                        Intent intent = new Intent(SplashActivity.this, WebActivity_.class);
                                        intent.putExtra(Constant.ACTION_AD_URL, link);
                                        startActivity(intent);
                                        finish();
                                    }
                                });
                            }
                            next();
                        } else {
                            nextNow();
                        }
                    }
                });

            }
        }).start();

    }

    public static boolean testUrlWithTimeOut(String urlString,int timeOutMillSeconds){
        /*URL url;
        try {
            url = new URL(urlString);
            URLConnection co =  url.openConnection();
            co.setConnectTimeout(timeOutMillSeconds);
            co.connect();
            return true;
        } catch (Exception e1) {
            url = null;
            return false;
        }*/
        URL url;
        try {
            url = new URL(urlString);
            HttpURLConnection con = (HttpURLConnection) url.openConnection();
            con.setConnectTimeout(timeOutMillSeconds);
            int state = con.getResponseCode();
            if (state == 200) {
               return true;
            }

        }catch (Exception ex) {
            return false;
        }
        return false;
    }

    private void requestServers(){
        Call call = ApiClient.getApiService().getServers();
        addJob(call);
        call.enqueue(new RestCallBack<ActiveservsResponse>() {
            @Override
            public void success(ActiveservsResponse response) {
                try {
                    if(null != response && null != response.getList()){
                        Gson gson = new Gson();
                        SecurePreferences.getInstance().edit().putString("preference_active_servs", gson.toJson(response.getList())).commit();
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }
            }

            @Override
            public void failure(RestError error) {
                ToastUtil.showToastShort(error.msg);
            }
        });
    }

    private void requestNotices(){
        Call noticeCall = ApiClient.getApiService().queryNoticeList();
        addJob(noticeCall);
        noticeCall.enqueue(new RestCallBack<NoticeResponse>() {
            @Override
            public void success(NoticeResponse response) {
                try {
                    CacheTools.noticeList = response.list;
                }catch (Exception e){
                    e.printStackTrace();
                }
            }

            @Override
            public void failure(RestError error) {
                ToastUtil.showToastShort(error.msg);
            }
        });
    }

    void nextNow() {
        if (UserManager.isLogin()) {
            Intent intent = new Intent(this, MainActivity_.class);
            startActivity(intent);
        }else{
            Intent intent = new Intent(this, LoginActivity_.class);
            startActivity(intent);
        }
        finish();
    }

    @UiThread(delay = 2000)
    void next() {
        nextNow();
    }


}
